package com.steven.team.utils;

import java.util.HashMap;
import java.util.Map;

public class FileTypeUtils {
    private static FileTypeUtils instance = null;

    private FileTypeUtils() {
    }

    private static FileTypeUtils getInstance() {
        if (instance == null)
            instance = new FileTypeUtils();
        instance.init();
        return instance;
    }

    public Map<String, String> FILE_TYPE_MAP = new HashMap<String, String>();

    private void init() {
        FILE_TYPE_MAP.put("ffd8ff", "jpg"); //JPEG (jpg)
        FILE_TYPE_MAP.put("89504e47", "png"); //PNG (png)
    }

    public static String getFileTypeByStream(byte[] b) {
        String filetypeHex = String.valueOf(getFileHexString(b));
        for (Map.Entry<String, String> entry : getInstance().FILE_TYPE_MAP.entrySet()) {
            String fileTypeHexValue = entry.getKey().toUpperCase();
            if (filetypeHex.toUpperCase().startsWith(fileTypeHexValue)) {
                return entry.getValue();
            }
        }
        return null;
    }

    private static String getFileHexString(byte[] b) {
        StringBuilder stringBuilder = new StringBuilder();
        if (b == null || b.length <= 0) {
            return null;
        }
        for (byte value : b) {
            int v = value & 0xFF;
            String hv = Integer.toHexString(v);
            if (hv.length() < 2) {
                stringBuilder.append(0);
            }
            stringBuilder.append(hv);
        }
        return stringBuilder.toString();
    }
}
